package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

import com.conversationboard.authenticator.AuthenticationCookie;
import com.conversationboard.cache.newanswers.NewAnswersThread;
import com.conversationboard.config.Configuration;
import com.conversationboard.controller.ipaddress.IPAddress;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.Role;
import com.conversationboard.model.User;
import com.conversationboard.site.Site;

/**
 * Viewing the new answers page.
 * 
 * @author Keith Watson
 */

@WebServlet(name = "NewAnswersControllerServlet", urlPatterns = "/NewAnswersControllerServlet")
public class NewAnswersControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 1750939883617057039L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Site.incrementPageHitCount();

		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		int boardId = Integer.parseInt(request.getParameter("boardid"));

		try {

			Principal principal = request.getUserPrincipal();

			String loginId = null;

			if (principal == null) {
				if (AuthenticationCookie.getUserName(request) != null) {
					response.sendRedirect(Configuration.getInstance().getRoot() + "/LoginControllerServlet?autologin=true&referrer=NewAnswersControllerServlet%3Fboardid=" + boardId);
					return;
				}
			}

			if (principal != null) {
				loginId = principal.getName();
			}

			User user = User.get(loginId);
			Board board = Boards.getBoard(boardId);

			/*
			 * Can probably remove this in time; it's just protecting against
			 * exceptions when people enter boards that don't exist. User should
			 * never be null as the anonymous user is returned.
			 */

			if (board == null || user == null) {
				return;
			}

			if (user.getRole() != Role.Anonymous) {
				user.setIpAddress(IPAddress.getIPAddress(request));
				user.setLastAccessed(new Date());
			}

			user.updateLastLoggedIn(IPAddress.getIPAddress(request));

			List<NewAnswersThread> threads = board.getThreadsWithNewAnswers();

			/*
			 * If you have requested that they be sorted alphabetically, then
			 * sort the output
			 */

			if (request.getParameter("sort") != null) {
				Collections.sort(threads);
				request.setAttribute("sort", true);
			}

			/* If it's a private board and you're not a member, you can't see it */

			if (board.isPrivateBoard() && !(user.isMemberOfBoard(boardId))) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
				dispatcher.forward(request, response);
				return;
			}

			if ((request.getParameter("xml") != null) && (request.getParameter("xml").equalsIgnoreCase("true"))) {

				int numberOfNewAnswers = 0;

				if (request.getParameter("number") != null) {
					numberOfNewAnswers = Integer.parseInt(request.getParameter("number"));
				}

				String stylesheet = request.getParameter("stylesheet");
				XmlNewAnswers.deliverAsXML(response, request.getContextPath(), stylesheet, numberOfNewAnswers, threads, user);

				return;
			}

			request.setAttribute("user", user);
			request.setAttribute("board", board);
			request.setAttribute("threads", threads);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/newanswers.jsp?boardId=" + boardId);

			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (ServletException e) {
			throw new ServletException(e);
		} catch (IOException e) {
			throw new ServletException(e);
		} catch (TransformerConfigurationException e) {
			throw new ServletException(e);
		} catch (TransformerException e) {
			throw new ServletException(e);
		}

	}

}
